const pool = require('../config/db');
const { generateToken } = require('../utils/auth');
const { sendVerificationCode } = require('../utils/sms');
const fileUpload = require('../utils/fileUpload');

// 商户登录
const login = async (req, res) => {
    try {
        const { phone, code } = req.body;
        
        // 验证验证码
        // TODO: 实现验证码验证逻辑
        
        // 查询商户信息
        const [users] = await pool.execute(
            'SELECT id, name, role, phone FROM users WHERE phone = ? AND role = "store"',
            [phone]
        );

        if (users.length === 0) {
            return res.status(401).json({
                code: 401,
                message: '商户不存在'
            });
        }

        const user = users[0];
        console.log('查询到的管理员信息:', user);

        // 生成token
        const tokenData = {
            id: user.id,
            role: user.role,
            phone: user.phone
        };
        console.log('生成的token信息:', tokenData);
        const token = generateToken(user.id, user.role);

        res.json({
            code: 200,
            data: {
                token,
                userInfo: {
                    id: user.id,
                    name: user.name,
                    phone: user.phone,
                    role: user.role
                }
            }
        });
    } catch (error) {
        console.error('商户登录失败:', error);
        res.status(500).json({
            code: 500,
            message: '登录失败'
        });
    }
};

// 发送验证码
const sendCode = async (req, res) => {
    try {
        const { phone } = req.body;
        
        // 生成6位验证码
        const code = Math.floor(100000 + Math.random() * 900000).toString();
        
        // 发送验证码
        const sent = await sendVerificationCode(phone, code);
        
        if (sent) {
            res.json({
                code: 200,
                message: '验证码发送成功'
            });
        } else {
            res.status(500).json({
                code: 500,
                message: '验证码发送失败'
            });
        }
    } catch (error) {
        console.error('发送验证码失败:', error);
        res.status(500).json({
            code: 500,
            message: '发送验证码失败'
        });
    }
};

// 获取商户概览数据
const getOverview = async (req, res) => {
    try {
        const { userId } = req.user;
        console.log('正在获取商户概览数据，userId:', userId);
        
        const connection = await pool.getConnection();

        try {
            // 1. 获取今日订单数
            const [todayOrdersResult] = await connection.execute(`
                SELECT COUNT(*) as count 
                FROM orders o
                JOIN stores s ON o.store_id = s.id
                WHERE s.owner_id = ? 
                AND DATE(o.create_time) = CURDATE()
            `, [userId]);
            console.log('今日订单查询结果:', todayOrdersResult);

            // 2. 获取进行中的优惠券数量
            const [activeCouponsResult] = await connection.execute(`
                SELECT COUNT(*) as count 
                FROM coupons c
                JOIN stores s ON c.store_id = s.id
                WHERE s.owner_id = ? 
                AND c.expire_date >= CURDATE()
            `, [userId]);
            console.log('进行中优惠券查询结果:', activeCouponsResult);

            // 3. 获取总收入
            const [totalRevenueResult] = await connection.execute(`
                SELECT COALESCE(SUM(o.final_price), 0) as total 
                FROM orders o
                JOIN stores s ON o.store_id = s.id
                WHERE s.owner_id = ? 
                AND o.status = 'completed'
            `, [userId]);
            console.log('总收入查询结果:', totalRevenueResult);

            // 4. 检查商户是否存在
            const [stores] = await connection.execute(
                'SELECT * FROM stores WHERE owner_id = ?',
                [userId]
            );
            console.log('商户店铺信息:', stores);

            const data = {
                todayOrders: 0,
                activeCoupons: 0,
                totalRevenue: '0.00'
            };

            if (todayOrdersResult && todayOrdersResult[0]) {
                data.todayOrders = Number(todayOrdersResult[0].count);
            }

            if (activeCouponsResult && activeCouponsResult[0]) {
                data.activeCoupons = Number(activeCouponsResult[0].count);
            }

            if (totalRevenueResult && totalRevenueResult[0]) {
                const total = Number(totalRevenueResult[0].total);
                data.totalRevenue = isNaN(total) ? '0.00' : total.toFixed(2);
            }

            console.log('返回的数据:', data);

            res.json({
                code: 200,
                data
            });
        } finally {
            connection.release();
        }
    } catch (error) {
        console.error('获取商户概览数据失败:', error);
        res.status(500).json({
            code: 500,
            message: '获取商户概览数据失败'
        });
    }
};

// 获取店铺信息
const getStoreInfo = async (req, res) => {
    try {
        const { userId } = req.user;
        const [stores] = await pool.execute(
            'SELECT * FROM stores WHERE owner_id = ?',
            [userId]
        );

        if (stores.length === 0) {
            return res.status(404).json({
                code: 404,
                message: '店铺信息不存在'
            });
        }

        res.json({
            code: 200,
            data: stores[0]
        });
    } catch (error) {
        console.error('获取店铺信息失败:', error);
        res.status(500).json({
            code: 500,
            message: '获取店铺信息失败'
        });
    }
};

// 更新店铺信息
const updateStoreInfo = async (req, res) => {
    try {
        const { userId } = req.user;
        const {
            name,
            type,
            address,
            contact_person,
            contact_phone,
            description,
            open_time,
            close_time,
            latitude,
            longitude,
            is_open
        } = req.body;

        await pool.execute(
            `UPDATE stores 
             SET name = ?, type = ?, address = ?, contact_person = ?, 
                 contact_phone = ?, description = ?, open_time = ?, close_time = ?,
                 latitude = ?, longitude = ?, is_open = ?
             WHERE owner_id = ?`,
            [name, type, address, contact_person, contact_phone, description, 
             open_time, close_time, latitude, longitude, is_open, userId]
        );

        res.json({
            code: 200,
            message: '店铺信息更新成功'
        });
    } catch (error) {
        console.error('更新店铺信息失败:', error);
        res.status(500).json({
            code: 500,
            message: '更新店铺信息失败'
        });
    }
};

// 上传店铺Logo
const uploadLogo = async (req, res) => {
    try {
        const { userId } = req.user;
        
        if (!req.files || !req.files.logo) {
            return res.status(400).json({
                code: 400,
                message: '请选择要上传的Logo'
            });
        }

        const logo = req.files.logo;
        const uploadResult = await fileUpload.uploadFile(logo, 'store-logos');

        if (uploadResult.success) {
            await pool.execute(
                'UPDATE stores SET logo = ? WHERE owner_id = ?',
                [uploadResult.url, userId]
            );

            res.json({
                code: 200,
                data: {
                    url: uploadResult.url
                },
                message: 'Logo上传成功'
            });
        } else {
            throw new Error('文件上传失败');
        }
    } catch (error) {
        console.error('上传Logo失败:', error);
        res.status(500).json({
            code: 500,
            message: '上传Logo失败'
        });
    }
};

// 获取订单列表
const getOrders = async (req, res) => {
    try {
        const { userId } = req.user;
        const { status, page = 1, limit = 10 } = req.query;
        
        const offset = (page - 1) * limit;
        let statusCondition = '';
        if (status) {
            statusCondition = 'AND o.status = ?';
        }

        const [orders] = await pool.execute(
            `SELECT o.* 
             FROM orders o
             JOIN stores s ON o.store_id = s.id
             WHERE s.owner_id = ? ${statusCondition}
             ORDER BY o.create_time DESC
             LIMIT ? OFFSET ?`,
            status ? [userId, status, parseInt(limit), offset] : [userId, parseInt(limit), offset]
        );

        res.json({
            code: 200,
            data: orders
        });
    } catch (error) {
        console.error('获取订单列表失败:', error);
        res.status(500).json({
            code: 500,
            message: '获取订单列表失败'
        });
    }
};

// 获取订单详情
const getOrderDetail = async (req, res) => {
    try {
        const { userId } = req.user;
        const { id } = req.params;

        const [orders] = await pool.execute(
            `SELECT o.*, s.name as store_name, u.name as user_name
             FROM orders o
             JOIN stores s ON o.store_id = s.id
             JOIN users u ON o.user_id = u.id
             WHERE s.owner_id = ? AND o.id = ?`,
            [userId, id]
        );

        if (orders.length === 0) {
            return res.status(404).json({
                code: 404,
                message: '订单不存在'
            });
        }

        // 获取订单项
        const [orderItems] = await pool.execute(
            'SELECT * FROM order_items WHERE order_id = ?',
            [id]
        );

        res.json({
            code: 200,
            data: {
                ...orders[0],
                items: orderItems
            }
        });
    } catch (error) {
        console.error('获取订单详情失败:', error);
        res.status(500).json({
            code: 500,
            message: '获取订单详情失败'
        });
    }
};

// 更新订单状态
const updateOrderStatus = async (req, res) => {
    try {
        const { userId } = req.user;
        const { id } = req.params;
        const { status } = req.body;

        const [result] = await pool.execute(
            `UPDATE orders o
             JOIN stores s ON o.store_id = s.id
             SET o.status = ?
             WHERE s.owner_id = ? AND o.id = ?`,
            [status, userId, id]
        );

        if (result.affectedRows === 0) {
            return res.status(404).json({
                code: 404,
                message: '订单不存在或无权限更新'
            });
        }

        res.json({
            code: 200,
            message: '订单状态更新成功'
        });
    } catch (error) {
        console.error('更新订单状态失败:', error);
        res.status(500).json({
            code: 500,
            message: '更新订单状态失败'
        });
    }
};

// 创建优惠券
const createCoupon = async (req, res) => {
    try {
        const { userId } = req.user;
        const { title, amount, minAmount, totalCount, startDate, endDate } = req.body;

        // 获取商户的店铺ID
        const [stores] = await pool.execute(
            'SELECT id FROM stores WHERE owner_id = ?',
            [userId]
        );

        if (stores.length === 0) {
            return res.status(404).json({
                code: 404,
                message: '店铺不存在'
            });
        }

        const storeId = stores[0].id;

        // 根据数据库表结构创建优惠券 - 移除title字段
        await pool.execute(
            `INSERT INTO coupons (store_id, amount, coupon_condition, expire_date, type)
             VALUES (?, ?, ?, ?, 'store')`,
            [storeId, parseFloat(amount) || 0, minAmount ? `满${minAmount}元可用` : '无门槛', endDate || null]
        );

        res.json({
            code: 200,
            message: '优惠券创建成功'
        });
    } catch (error) {
        console.error('创建优惠券失败:', error);
        res.status(500).json({
            code: 500,
            message: '创建优惠券失败'
        });
    }
};

// 获取优惠券列表
const getCoupons = async (req, res) => {
    try {
        const { userId } = req.user;
        const { status } = req.query;

        let statusCondition = '';
        if (status === 'active') {
            statusCondition = 'AND c.expire_date >= CURDATE()';
        } else if (status === 'expired') {
            statusCondition = 'AND c.expire_date < CURDATE()';
        }

        const [coupons] = await pool.execute(
            `SELECT c.* 
             FROM coupons c
             JOIN stores s ON c.store_id = s.id
             WHERE s.owner_id = ? ${statusCondition}
             ORDER BY c.created_at DESC`,
            [userId]
        );

        res.json({
            code: 200,
            data: coupons
        });
    } catch (error) {
        console.error('获取优惠券列表失败:', error);
        res.status(500).json({
            code: 500,
            message: '获取优惠券列表失败'
        });
    }
};

// 停用优惠券
const disableCoupon = async (req, res) => {
    try {
        const { userId } = req.user;
        const { id } = req.params;
        
        // 获取优惠券信息和商户的店铺ID
        const [coupons] = await pool.execute(
            `SELECT c.* 
             FROM coupons c
             JOIN stores s ON c.store_id = s.id
             WHERE s.owner_id = ? AND c.id = ?`,
            [userId, id]
        );
        
        if (coupons.length === 0) {
            return res.status(404).json({
                code: 404,
                message: '优惠券不存在或无权限操作'
            });
        }
        
        // 更新优惠券状态，将received_count设置为一个较大值（如9999），使其不可再领取
        await pool.execute(
            `UPDATE coupons c
             JOIN stores s ON c.store_id = s.id
             SET c.received_count = 9999
             WHERE s.owner_id = ? AND c.id = ?`,
            [userId, id]
        );
        
        res.json({
            code: 200,
            message: '优惠券已停用'
        });
    } catch (error) {
        console.error('停用优惠券失败:', error);
        res.status(500).json({
            code: 500,
            message: '停用优惠券失败'
        });
    }
};

module.exports = {
    login,
    sendCode,
    getOverview,
    getStoreInfo,
    updateStoreInfo,
    uploadLogo,
    getOrders,
    getOrderDetail,
    updateOrderStatus,
    createCoupon,
    getCoupons,
    disableCoupon
}; 